package com.payment.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.payment.common.Aliconfig.AlipayConfig;
import com.payment.common.utils.DateUtils;
import com.payment.common.utils.LocalDateTimeUtils;
import com.payment.entity.po.PayOrder;
import com.payment.entity.vo.PayVO;
import com.payment.common.utils.ResultDataDto;
import com.payment.mapper.PayOrderMapper;
import com.payment.service.AliService;
import com.payment.service.TrainingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Author: Dgg
 * @Date: 2021/4/2 10:19
 */
@Service("AliService")
public class AliServiceImpl implements AliService {
	private static final Logger logger = LoggerFactory.getLogger(AliServiceImpl.class);
	@Resource
	private AlipayConfig alipayConfig;
	@Resource
	private TrainingService trainingService;
	@Resource
	private PayOrderMapper payOrderMapper;
	@Override
	public ResultDataDto AliPayCode(PayVO payVO) {
		String outTradeNo = payVO.getOutTradeNo();
		String totalAmount = payVO.getTotalAmount();
		String timeoutExpress = alipayConfig.getTimeOutExpress();
		//即用户在支付宝客户端内出示的付款码，使用一次即失效，需要刷新后再去付款
		String authCode = payVO.getAuthCode();
		String storeId = payVO.getStoreId();
		String subject = payVO.getBody();
		/**
		 * 将订单内容入库
		 */
		PayOrder payOrder = new PayOrder();
		payOrder.setOutTradeNo(outTradeNo);
		payOrder.setTotalAmount(new BigDecimal(totalAmount));
		payOrder.setCreateTime(LocalDateTime.now());
		payOrder.setTimeoutExpress(timeoutExpress);
		payOrder.setSubject(subject);
		payOrder.setStoreId(storeId);
		payOrder.setPayType(Integer.parseInt(payVO.getPayType()));
		payOrder.setPayStatus(2);
		payOrder.setPaymentMethod(1);
		int insert = payOrderMapper.insert(payOrder);
		AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGateWayUrl(),
				alipayConfig.getAppId(),
				alipayConfig.getAliPayPrivateKey(), alipayConfig.getFormat(), alipayConfig.getCharset(),
				alipayConfig.getAliPayPublicKey(),
				alipayConfig.getSignType());
		String content = "{" +
				"\"out_trade_no\":\"" + outTradeNo + "\"," +
				"\"scene\":\"bar_code\"," + //scene：支付场景，条码付场景固定为 bar_code
				"\"auth_code\":\"" + authCode + "\"," +
				"\"subject\":\"" + subject + "\"," +
				"\"store_id\":\"" + storeId + "\"," +
				"\"timeout_express\":\"" + timeoutExpress + "\"," +
				"\"total_amount\":\"" + totalAmount + "\"" +
				"}";  //设置业务参数
		AlipayTradePayRequest alipayRequest = new AlipayTradePayRequest();
		alipayRequest.setBizContent(content);
		try {
			//请求
			AlipayTradePayResponse response = alipayClient.execute(alipayRequest);
			if (response != null && "10000".equals(response.getCode())) {
				/*
				 * 入库信息
				 */
				logger.info("订单号：{} 支付成功！", outTradeNo, response.getSubMsg());
				PayOrder payOrder1 = new PayOrder(payOrder.getId(),null,null,null,null,null,null,null,null,response.getTradeNo(),null,null,response.getSubMsg(),response.getSubCode(),response.getCode(),response.getMsg(),null,response.getTradeNo(),alipayConfig.getAppId(),null,response.getBuyerUserId(),null,null, LocalDateTimeUtils.convertDateToLDT(response.getGmtPayment()),null,null,null,null,1,null,null);
				payOrderMapper.updateById(payOrder1);
				return ResultDataDto.ok("支付宝支付成功！",outTradeNo);
			} else if (response != null && "10003".equals(response.getCode())) {
				logger.info("订单号：{} 等待用户付款！及时查询支付结果", outTradeNo, response.getSubMsg());
				int result = trainingService.payTraining(outTradeNo,payVO.getPayType());
				switch (result){
					case 200:
						return ResultDataDto.ok("支付宝支付成功！",outTradeNo);
					case 201:
						return new ResultDataDto("201","超时支付订单关闭",outTradeNo);
					case 500:
						return new ResultDataDto("500","未知异常",outTradeNo);
					case 501:
						return new ResultDataDto("501","订单长时间未支付撤销订单操作失败",outTradeNo);
					default:
						return new ResultDataDto("500","未知异常",outTradeNo);
				}
			} else if (response != null && "20000".equals(response.getCode())) {
				logger.error("订单号：{} 系统异常，请及时查询支付结果！", outTradeNo, response.getSubMsg());
				return new ResultDataDto("500","系统异常，请及时查询支付结果！",outTradeNo);
			} else if (response != null && "40002".equals(response.getCode())) {
				logger.error("订单号：{} 订单参数不合法，支付失败！", outTradeNo, response.getSubMsg());
				return ResultDataDto.error(outTradeNo);
			} else if (response != null && "40004".equals(response.getCode())) {
				if ("ACQ.PAYMENT_AUTH_CODE_INVALID".equals(response.getSubCode())) {
					logger.error("订单号：{} 付款码无效，支付失败！", outTradeNo, response.getSubMsg());
					return ResultDataDto.error(outTradeNo);
				} else if ("ACQ.INVALID_PARAMETER".equals(response.getSubCode())) {
					logger.error("订单号：{} 订单参数不合法，支付失败！", outTradeNo, response.getSubMsg());
					return ResultDataDto.error(outTradeNo);
				}
				logger.error("订单号：{} 支付宝支付失败", outTradeNo, response.getSubMsg());
				return ResultDataDto.error(outTradeNo);
			} else {
				logger.error("订单号：{} 支付宝支付失败", outTradeNo, response.getSubMsg());
				return ResultDataDto.error(outTradeNo);
			}
		} catch (AlipayApiException e) {
			logger.error("订单号：{} 支付宝支付调用异常", outTradeNo);
			e.printStackTrace();
			return ResultDataDto.error("支付宝支付调用异常");
		} catch (Exception e) {
			e.printStackTrace();
			return ResultDataDto.error("支付宝支付调用异常");
		}
	}
}
